package com.lap.framework.junit.configure;

import com.lap.framework.common.tool.JsonUtil;
import com.lap.framework.junit.configure.model.FileConfigure;
import com.lap.framework.junit.shared.exception.ConfigError;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.Yaml;

@Slf4j
public class ConfigLoader {

  public static EnvConfigure load() {
    Yaml yaml = new Yaml();
    try {
      ClassPathResource resource = new ClassPathResource("config.yaml");
      try (InputStream inputStream = resource.getInputStream()) {
        EnvConfigure config = yaml.loadAs(inputStream, EnvConfigure.class);
        validateConfig(config);
        log.info("loader yaml :{}", JsonUtil.pretty(config));
        return config;
      }
    } catch (IOException e) {
      throw new ConfigError("loader yaml error:", e);
    }
  }

  private static void validateConfig(EnvConfigure config) {
    if (config == null) {
      throw new ConfigError("配置不能为空");
    }

    if (config.getBasePackages() == null || config.getBasePackages().isEmpty()) {
      throw new ConfigError("basePackages 不能为空");
    }

    if (config.getSupperClass() == null || config.getSupperClass().trim().isEmpty()) {
      throw new ConfigError("superClass 不能为空");
    }

    if (config.getFileConfigure() == null) {
      config.setFileConfigure(new FileConfigure());
    }

    if (config.getFileConfigure().getFileList() == null) {
      config.getFileConfigure().setFileList(new ArrayList<>());
    }
  }
}
